import { editUser, delUser, resetUser } from '@/api/user'

const getDefaultState = () => {
  return {
    loading: false,
    tableData: [],
    current: 1,
    size: 18,
    total: 0,
    conditions: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  UPDATE_CONDITIONS: (state, payload = {}) => {
    const { conditions } = state
    state.conditions = payload ? { ...conditions, ...payload } : {}
  }
}

const actions = {
  // 编辑用户
  async onEditUser({ dispatch, commit }, payload = {}) {
    const { success } = await editUser(payload)
    if (success) {
      dispatch('hideModal', {}, { root: true })
      commit('UPDATE_CONDITIONS')
    }
  },

  // 重置
  async onResetUser({ dispatch }, payload = {}) {
    const { code, userName, realName, modalKey } = payload
    const { success, retData } = await resetUser(code)

    if (success) {
      const nameStr = `${userName}(${realName})`

      dispatch(
        'showModal',
        {
          modalKey,
          modalData: {
            nameStr,
            newPwd: retData || 'xm123456'
          }
        },
        { root: true }
      )
    }
  },

  // 删除
  async onDelUser({ commit }, payload = {}) {
    const { code } = payload
    const { success } = await delUser(code)
    if (success) {
      commit('UPDATE_CONDITIONS')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
